from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
import datetime


# Create your views here.


class UserView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_obj = UserModel.objects.filter(username=username).first()
        if not user_obj:
            return Response({'msg': '没有该会员', 'code': 400})
        elif user_obj.password != password:
            return Response({'msg': '密码错误', 'code': 400})
        else:
            ser = UserSer(user_obj).data
            return Response({'msg': '欢迎进入本餐厅', 'user': ser, 'code': 200})

    def get(self, request):
        user = UserModel.objects.exclude(level=0)
        return Response


class GoodsView(APIView):
    def get(self, request):
        set = GoodsModel.objects.all()
        ser = GoodsSer(set, many=True).data
        return Response(ser)


class RecordView(APIView):
    def post(self, request):
        user_id = request.data.get('user_id')
        goods_id = request.data.get('goods_id')
        record_obj = RecordModel.objects.filter(user_id=user_id, goods_id=goods_id, money=None).first()
        if record_obj:
            return Response({'msg': '正在食用中', 'code': 400})
        RecordModel.objects.create(user_id=user_id, goods_id=goods_id)
        return Response({'msg': '开始食用', 'code': 200})

    def put(self, request):
        user_id = request.data.get('user_id')
        goods_id = request.data.get('goods_id')
        user_obj = UserModel.objects.filter(id=user_id).first()
        user_gly = UserModel.objects.filter(level=0).first()
        goods_obj = GoodsModel.objects.filter(id=goods_id).first()
        record_obj = RecordModel.objects.filter(user_id=user_id, money=None).first()
        if record_obj:
            price = goods_obj.price # 套餐价格
            end = datetime.datetime.now()  # 当前时间
            time_s = round((end - record_obj.start).total_seconds())  # 多少秒
            if time_s < 1:
                time_s = 1
            time = round(time_s / 60)   # 换算分钟
            new_money = price * time    # 消费金额
            if new_money > 3000:
                money = new_money * 0.8
            elif new_money > 5000:
                money = new_money * 0.5
            else:
                money = new_money
            record_obj.end = end
            record_obj.time = time_s
            record_obj.money = money
            record_obj.save()
            user_obj.money += money
            user_obj.save()
            user_gly.money += money
            user_gly.save()
            goods_obj.num += 1
            goods_obj.save()
            return Response({'msg': '结算成功', 'code': 200})
        else:
            return Response({'msg': '结算失败', 'code': 400})